package com.hcloud.auth.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 重写jdbc的servcice，主要作用在于将clients进行缓存
 * 刚开始想放在redis的，然而觉得估计clients不会很多，就干脆放了一个Map
 * 当对clients有所修改的话，需要调用clearCache清除缓存
 *
 * @Auther hepangui
 * @Date 2018/11/12
 */
@Slf4j
public class MyJdbcClientDetailsService extends JdbcClientDetailsService {

    private static final Map<String, ClientDetails> clients = new HashMap<>();

    public static void clearCache() {
        clients.clear();
    }

    public MyJdbcClientDetailsService(DataSource dataSource) {
        super(dataSource);
    }

    /**
     * 重写原生方法支持缓存
     *
     * @param clientId
     * @return
     * @throws InvalidClientException
     */
    @Override
    public ClientDetails loadClientByClientId(String clientId) throws InvalidClientException {
        ClientDetails clientDetails = clients.get(clientId);
        if (clientDetails != null) {
            log.debug("直接返回缓存：{}",clientId);
            return clientDetails;
        }
        ClientDetails clientDetails1 = super.loadClientByClientId(clientId);
        clients.put(clientId, clientDetails1);
        return clientDetails1;
    }
}
